#include <bits/stdc++.h>
// 2025/02/23
// tag: 
// Author: Forever
using namespace std;

const int maxn = 1000001;

int n, p[maxn], w[maxn], val[maxn], ans[maxn], dep[maxn];
vector<int> edge[maxn];

using int64 = int64_t;

void init(int pos = 0, int depth = 0){
    dep[pos] = depth;
    for (auto i : edge[pos])
        init(i, depth + 1);  
}

int help(int pos){
    int k = pos, flag = 0, cnt = 0;
    while (k != 0){
        if (val[k]){
            flag = cnt;
            break;
        }
        val[k]++, k = p[k], cnt++;
    }
    if (val[k] && flag == 0)
        flag = cnt;
    val[k]++;
    if (flag == 0)
        return 0;
    return dep[pos] - flag + 1;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> p[i], edge[p[i]].push_back(i);
    int cnt = 0;
    for (int i = 1; i <= n; i++)
        if (edge[i].size() == 0)
            cnt++;
    init();
    for (int i = 1; i <= cnt; i++)
        cin >> w[i];
    for (int i = cnt; i >= 1; i--){
        ans[i] = help(w[i]);
    }
    for (int i = 1; i <= cnt; i++)
        cout << ans[i] << endl;
    return 0;
}